//
//  ExtentionsTableViewController.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2017/10/27.
//  Copyright © 2021年 梁慧聪. All rights reserved.
//

#import "CLVCExtentions.h"
#import "CLSettingSwitchTableViewCell.h"
#import "CLUserDefaults.h"
#import "CLJavaScriptHelper.h"
#import "CLWebViewManager.h"
#import "CLSettingSwitchReuseView.h"
static NSString *const kExtentionsTableViewSwitchCellIdentifier = @"ExtentionsTableViewSwitchCellIdentifier";
static NSString *const kExtentionsTableViewDefaultCellIdentifier = @"ExtentionsTableViewDefaultCellIdentifier";

typedef NS_ENUM(NSUInteger, CLExtentionType) {
    CLExtentionTypeOfNoImage,
    CLExtentionTypeOfBlockBaiduAD,
    CLExtentionTypeOfEyeProtective,
    CLExtentionTypeOfNight,
    CLExtentionTypeCache
};

@interface CLVCExtentionModel : NSObject
@property (nonatomic, assign) CLExtentionType type;
@property (nonatomic, copy) NSString *key;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *des;
@property (nonatomic, strong) NSArray *options;
@end
@implementation CLVCExtentionModel
@end


@interface CLVCExtentions ()
@property (nonatomic, strong) NSIndexPath *eyeColorIndexPath;
@property (nonatomic, copy) NSArray <CLVCExtentionModel *>*dataSource;
@end

@implementation CLVCExtentions

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"扩展";
    
    NSMutableArray *dataSource = [NSMutableArray array];
    CLVCExtentionModel *noImg = [[CLVCExtentionModel alloc]init];
    noImg.type = CLExtentionTypeOfNoImage;
    noImg.key = KeyNoImageModeStatus;
    noImg.title = @"无图模式";
    noImg.des = @"注意：无图模式仅对图片进行了隐藏，浏览器依然会发起图片资源请求";
    [dataSource addObject:noImg];
    
    CLVCExtentionModel *baiduAd = [[CLVCExtentionModel alloc]init];
    baiduAd.type = CLExtentionTypeOfBlockBaiduAD;
    baiduAd.key = KeyBlockBaiduADStatus;
    baiduAd.title = @"去除百度广告";
    baiduAd.des = @"去除百度搜索页面广告及banner推广,基于https://greasyfork.org/scripts/24192-kill-baidu-ad/code/Kill%20Baidu%20AD.user.js代码修改,感谢作者@hoothin";
    [dataSource addObject:baiduAd];
    
//    CLVCExtentionModel *eyeProtect = [[CLVCExtentionModel alloc]init];
//    eyeProtect.type = CLExtentionTypeOfEyeProtective;
//    eyeProtect.key = KeyEyeProtectiveStatus;
//    eyeProtect.title = @"护眼模式";
//    eyeProtect.des = @"护眼扩展,修改网页背景色,关闭护眼功能需刷新页面才能生效";
//    eyeProtect.options = @[@"乡土黄",@"豆沙绿",@"浅色灰",@"淡橄榄",@"黑夜"];
//    [dataSource addObject:eyeProtect];
    
    CLVCExtentionModel *night = [[CLVCExtentionModel alloc]init];
    night.type = CLExtentionTypeOfNight;
    night.key = CLKeyNightStatus;
    night.title = @"黑夜模式";
    night.des = @"黑夜模式,测试版本";
    
    [dataSource addObject:night];
    
    self.dataSource = dataSource;

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kExtentionsTableViewDefaultCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CLSettingSwitchReuseView class]) bundle:nil] forHeaderFooterViewReuseIdentifier:[CLSettingSwitchReuseView identifier]];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    CLVCExtentionModel *model = self.dataSource[section];
    if (model.type == CLExtentionTypeOfEyeProtective) {
        return [CLUserDefaults boolForKey:KeyEyeProtectiveStatus] ? model.options.count : 0;
    }
    return model.options.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CLVCExtentionModel *model = self.dataSource[section];
    CLSettingSwitchReuseView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[CLSettingSwitchReuseView identifier]];
    view.leftLabel.text = model.title;
    [view.switchControl setOn:[CLUserDefaults boolForKey:model.key]];
    view.valueChangedBlock = ^(UISwitch *sw) {
        [CLUserDefaults setBool:sw.on forKey:model.key];
        switch (model.type) {
            case CLExtentionTypeOfNoImage:
            {
                [Notifier postNotification:[NSNotification notificationWithName:kNoImageModeChanged object:nil]];
            }
                break;
            case CLExtentionTypeOfBlockBaiduAD:
            {
                NSMutableArray<NSIndexPath *> *array = [NSMutableArray arrayWithCapacity:4];
                for (int i = 1; i < 6; i++) {
                    [array addObject:[NSIndexPath indexPathForRow:i inSection:CLExtentionTypeOfEyeProtective]];
                }
                if (sw.on) {
                    //[JavaScriptHelper setEyeProtectiveWithWebView:[TabManager sharedInstance].browserContainerView.webView on:YES loadPrimaryScript:YES];
                    [tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationTop];
                }
                else {
                    //[JavaScriptHelper setEyeProtectiveWithWebView:[TabManager sharedInstance].browserContainerView.webView on:NO loadPrimaryScript:YES];
                    [tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationBottom];
                }
            }
                break;
            case CLExtentionTypeOfEyeProtective:
            {
                [tableView reloadData];
            }
                break;
            case CLExtentionTypeOfNight:
            {
                if (@available(iOS 13.0, *)) {
                    if (sw.on) {
                        [[CLSharedAppDelegate getRootWindow] setOverrideUserInterfaceStyle:UIUserInterfaceStyleDark];
                    } else {
                        [[CLSharedAppDelegate getRootWindow] setOverrideUserInterfaceStyle:UIUserInterfaceStyleLight];
                    }
                }
                [Notifier postNotification:[NSNotification notificationWithName:kNightStatueModeChanged object:nil]];
                [tableView reloadData];
            }
                break;
        }
    };
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CLVCExtentionModel *model = self.dataSource[indexPath.section];
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kExtentionsTableViewDefaultCellIdentifier];
    cell.textLabel.text = @"";
    if (model.type == CLExtentionTypeOfEyeProtective) {
        cell.textLabel.text = model.options[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryNone;
        if ([[CLUserDefaults stringForKey:CLKeyThemeName] isEqualToString:cell.textLabel.text]) {
            self.eyeColorIndexPath = indexPath;
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return self.dataSource[section].des;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CLVCExtentionModel *model = self.dataSource[indexPath.section];
    if (model.type == CLExtentionTypeOfEyeProtective) {
        if (self.eyeColorIndexPath && !([self.eyeColorIndexPath compare:indexPath] == NSOrderedSame)) {
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:self.eyeColorIndexPath];
            cell.accessoryType = UITableViewCellAccessoryNone;
            [Notifier postNotificationName:kEyeProtectiveModeChanged object:nil];
        }
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [CLUserDefaults setString:model.options[indexPath.row] forKey:CLKeyThemeName];
        self.eyeColorIndexPath = indexPath;
    }
}
@end
